package com.liu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liu.common.CustomException;
import com.liu.dto.SetmealDto;
import com.liu.entity.Setmeal;
import com.liu.entity.SetmealDish;
import com.liu.mapper.SetmealMapper;
import com.liu.service.SetmealDishService;
import com.liu.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {


    @Resource
    private SetmealDishService setmealDishService;

    @Override
    public void saveSetmeslWithDish(SetmealDto setmealDto) {
        // 保存套餐信息
        this.save(setmealDto);

        //从setmealDto中拿到setmealDishes集合
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();

        //遍历集合并将套餐id存入套餐菜品关系表中
        List<SetmealDish> list = setmealDishes.stream().map(dish -> {
            dish.setSetmealId(setmealDto.getId());
            return dish;
        }).collect(Collectors.toList());

        //保存套餐菜品关系信息存入数据库表
        setmealDishService.saveBatch(list);

    }

    @Transactional
    public void removeWithDish(List<Long> ids) {
        //查询套餐状态，确定是否可以删除
        //select count(*) from setmeal where id in (1,2,3) and status = 1
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId, ids);
        queryWrapper.eq(Setmeal::getStatus, 1);

        //如果有套餐状态为起售，不能删除抛出异常
        if (this.count(queryWrapper) > 0) {

            throw new CustomException("套餐正在售卖中，不能删除");
        }

        //删除套餐表中的数据
        this.removeByIds(ids);

        //删除和套餐关联的菜品信息
        //delete from setmeal_dish where setmeal_id in (1,2,3)
        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(SetmealDish::getSetmealId, ids);
        //删除关系表中的数据----setmeal_dish
        setmealDishService.remove(lambdaQueryWrapper);

    }

    /**
     * 通过id查询套餐信息和菜品信息
     *
     * @param id
     * @return
     */
    @Override
    public SetmealDto getSetmealWithDish(Long id) {
        //通过id查询套餐信息
        Setmeal setmeal = this.getById(id);

        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal, setmealDto);

        //通过id查询套餐菜品信息
        List<SetmealDish> setmealDishes = setmealDishService.list(new LambdaQueryWrapper<SetmealDish>().eq(SetmealDish::getSetmealId, id));

        //封装dto返回
        setmealDto.setSetmealDishes(setmealDishes);
        return setmealDto;
    }


}
